package com.sj.hh.ui.community;

import android.animation.Animator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.mbt.deal.util.ToastUtil;
import com.sj.friendcircle.common.MomentsType;
import com.sj.friendcircle.common.router.RouterList;
import com.sj.friendcircle.lib.entity.ImageInfo;
import com.sj.friendcircle.lib.helper.AppFileHelper;
import com.sj.friendcircle.lib.manager.KeyboardControlMnanager;
import com.sj.friendcircle.lib.utils.ToolUtil;
import com.sj.friendcircle.ui.helper.PhotoHelper;
import com.sj.friendcircle.ui.imageloader.ImageLoadMnanger;
import com.sj.friendcircle.ui.util.AnimUtils;
import com.sj.friendcircle.ui.util.UIHelper;
import com.sj.friendcircle.ui.widget.commentwidget.CommentBox;
import com.sj.friendcircle.ui.widget.commentwidget.CommentWidget;
import com.sj.friendcircle.ui.widget.commentwidget.IComment;
import com.sj.friendcircle.ui.widget.common.TitleBar;
import com.sj.friendcircle.ui.widget.popup.SelectPhotoMenuPopup;
import com.sj.friendcircle.ui.widget.pullrecyclerview.CircleRecyclerView;
import com.sj.friendcircle.ui.widget.pullrecyclerview.interfaces.OnRefreshListener2;
import com.sj.hh.R;
import com.sj.hh.mvp.presenter.impl.MomentPresenter;
import com.sj.hh.mvp.view.IMomentView;
import com.sj.hh.request.MomentsRequest;
import com.sj.hh.request.base.OnResponseListener;
import com.sj.hh.request.exception.BmobException;
import com.sj.hh.ui.ActivityLauncher;
import com.sj.hh.ui.adapter.CircleMomentsAdapter;
import com.sj.hh.ui.friendcircle.CircleViewHelper;
import com.sj.hh.ui.friendcircle.viewholder.EmptyMomentsVH;
import com.sj.hh.ui.friendcircle.viewholder.MultiImageMomentsVH;
import com.sj.hh.ui.friendcircle.viewholder.TextOnlyMomentsVH;
import com.sj.hh.ui.friendcircle.viewholder.WebMomentsVH;
import com.sj.hh.util.OkHttp3Util;
import com.socks.library.KLog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.rongcloud.im.SealConst;
import cn.rongcloud.im.SealUserInfoManager;
import cn.rongcloud.im.server.network.http.HttpException;
import cn.rongcloud.im.server.response.PublishImageResponse;
import cn.rongcloud.im.server.response.friendcircle.CommentInfo;
import cn.rongcloud.im.server.response.friendcircle.FriendBackgroundResponse;
import cn.rongcloud.im.server.response.friendcircle.LikesInfo;
import cn.rongcloud.im.server.response.friendcircle.MomentsInfo;
import cn.rongcloud.im.server.utils.json.JsonMananger;
import cn.rongcloud.im.ui.activity.base.BaseCircleActivity;
import io.rong.imlib.model.UserInfo;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 社区主界面
 */

@Route(path = RouterList.CommunityActivity.path)
public class CommunityActivity extends BaseCircleActivity implements OnRefreshListener2, IMomentView, CircleRecyclerView.OnPreDispatchTouchListener {

    private static final int REQUEST_REFRESH = 0x20;
    private static final int REQUEST_LOADMORE = 0x11;
    private static final int LIST_FRIEND_BY_PAGE = 1;
    private static final int FRIEND_TRENDS_INFO = 2;


    private int clickServiceCount = 0;
    private RelativeLayout mTipsLayout;
    private TextView mServiceTipsView;
    private ImageView mCloseImageView;
    //服务器消息检查，非项目所需↑

    private CircleRecyclerView circleRecyclerView;
    private CommentBox commentBox;
    private HostViewHolder hostViewHolder;
    private CircleMomentsAdapter adapter;
    private List<MomentsInfo.DataBean> momentsInfoList;
    //request
    private MomentsRequest momentsRequest;
    private MomentPresenter presenter;

    private CircleViewHelper mViewHelper;
    private int pageNum = 1;
    private SharedPreferences sp;
    private String userId;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_circle);
        momentsInfoList = new ArrayList<>();
        momentsRequest = new MomentsRequest();
        sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        initView();
        initKeyboardHeightObserver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        AppFileHelper.initStroagePath(this);
    }

    @Override
    public void onHandleIntent(Intent intent) {

    }


    private void initView() {
        if (mViewHelper == null) {
            mViewHelper = new CircleViewHelper(this);
        }
        setTitle("社区");
        setTitleMode(TitleBar.MODE_BOTH);
        setTitleRightIcon(R.drawable.ic_camera);
        setTitleLeftText("社区");
        setTitleLeftIcon(R.drawable.back_left);
        presenter = new MomentPresenter(this);

        hostViewHolder = new HostViewHolder(this);
        circleRecyclerView = (CircleRecyclerView) findViewById(R.id.recycler);
        circleRecyclerView.setOnRefreshListener(this);
        circleRecyclerView.setOnPreDispatchTouchListener(this);
        circleRecyclerView.addHeaderView(hostViewHolder.getView());

        mTipsLayout = (RelativeLayout) findViewById(R.id.tips_layout);
        mServiceTipsView = (TextView) findViewById(R.id.service_tips);
        mCloseImageView = (ImageView) findViewById(R.id.iv_close);

        commentBox = (CommentBox) findViewById(R.id.widget_comment);
        commentBox.setOnCommentSendClickListener(onCommentSendClickListener);

        adapter = new CircleMomentsAdapter(this, momentsInfoList, presenter);
        adapter.addViewHolder(EmptyMomentsVH.class, MomentsType.EMPTY_CONTENT)
                .addViewHolder(MultiImageMomentsVH.class, MomentsType.MULTI_IMAGES)
                .addViewHolder(TextOnlyMomentsVH.class, MomentsType.TEXT_ONLY)
                .addViewHolder(WebMomentsVH.class, MomentsType.WEB);
        circleRecyclerView.setAdapter(adapter);
        circleRecyclerView.autoRefresh();

        userId = sp.getString(SealConst.SEALTALK_LOGIN_ID, "");
        request(FRIEND_TRENDS_INFO);
    }

    private void initKeyboardHeightObserver() {
        //观察键盘弹出与消退
        KeyboardControlMnanager.observerKeyboardVisibleChange(this, new KeyboardControlMnanager.OnKeyboardStateChangeListener() {
            View anchorView;

            @Override
            public void onKeyboardChange(int keyboardHeight, boolean isVisible) {
                int commentType = commentBox.getCommentType();
                if (isVisible) {
                    //定位评论框到view
                    anchorView = mViewHelper.alignCommentBoxToView(circleRecyclerView, commentBox, commentType);
                } else {
                    //定位到底部
                    commentBox.dismissCommentBox(false);
                    mViewHelper.alignCommentBoxToViewWhenDismiss(circleRecyclerView, commentBox, commentType, anchorView);
                }
            }
        });
    }

    @Override
    public Object doInBackground(int requestCode, String id) throws HttpException {
        switch (requestCode) {
            case LIST_FRIEND_BY_PAGE:
                return action.getListFriendByPage(pageNum, 0);
            case FRIEND_TRENDS_INFO:
                return action.friendTrendsInfo(userId);
        }
        return null;
    }

    @Override
    public void onSuccess(int requestCode, Object result) {
        super.onSuccess(requestCode, result);
        if (result != null) {
            switch (requestCode) {
                case LIST_FRIEND_BY_PAGE:

                    break;
                case FRIEND_TRENDS_INFO:
                    FriendBackgroundResponse response = (FriendBackgroundResponse) result;
                    if (response.getData() != null && response.getResultCode() == 0) {
                        if (hostViewHolder == null) return;
                        Glide.with(mContext).load(response.getData().getImgpath()).into(hostViewHolder.friend_wall_pic);
                    }
                    break;
            }
        }
    }

    @Override
    public void onRefresh() {
//        request(LIST_FRIEND_BY_PAGE);
        momentsRequest.setOnResponseListener(momentsRequestCallBack);
        momentsRequest.setRequestType(REQUEST_REFRESH);
        momentsRequest.setCurPage(0);
        momentsRequest.execute(mContext);
    }

    @Override
    public void onLoadMore() {
        momentsRequest.setOnResponseListener(momentsRequestCallBack);
        momentsRequest.setRequestType(REQUEST_LOADMORE);
        momentsRequest.execute(mContext);
    }


    //titlebar click


    @Override
    public void onTitleDoubleClick() {
        super.onTitleDoubleClick();
        if (circleRecyclerView != null) {
            int firstVisibleItemPos = circleRecyclerView.findFirstVisibleItemPosition();
            circleRecyclerView.getRecyclerView().smoothScrollToPosition(0);
            if (firstVisibleItemPos > 1) {
                circleRecyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        circleRecyclerView.autoRefresh();
                    }
                }, 200);
            }
        }

    }

    @Override
    public void onTitleRightClick() {
        new SelectPhotoMenuPopup(this).setOnSelectPhotoMenuClickListener(new SelectPhotoMenuPopup.OnSelectPhotoMenuClickListener() {
            @Override
            public void onShootClick() {
                PhotoHelper.fromCamera(CommunityActivity.this, false);
            }

            @Override
            public void onAlbumClick() {
                ActivityLauncher.startToPhotoSelectActivity(getActivity(), RouterList.PhotoSelectActivity.requestCode);
            }
        }).showPopupWindow();
    }

    @Override
    public boolean onTitleRightLongClick() {
        ActivityLauncher.startToPublishActivityWithResult(this, RouterList.PublishActivity.MODE_TEXT, null, RouterList.PublishActivity.requestCode);
        return true;
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RouterList.PhotoSelectActivity.requestCode && resultCode == RESULT_OK) {
            List<ImageInfo> selectedPhotos = data.getParcelableArrayListExtra(RouterList.PhotoSelectActivity.key_result);
            if (selectedPhotos != null) {
                ActivityLauncher.startToPublishActivityWithResult(this, RouterList.PublishActivity.MODE_MULTI, selectedPhotos, RouterList.PublishActivity.requestCode);
            }
        } else if (requestCode == RouterList.PublishActivity.requestCode && resultCode == RESULT_OK) {
            circleRecyclerView.autoRefresh();
        } else if (requestCode == RouterList.FriendCircleBg.requestCode && resultCode == RESULT_OK) {
            List<ImageInfo> selectedPhotos = data.getParcelableArrayListExtra(RouterList.PhotoSelectActivity.key_result);
            uploadBackgroundImageFile(selectedPhotos);
        } else {
            PhotoHelper.handleActivityResult(this, requestCode, resultCode, data, new PhotoHelper.PhotoCallback() {
                @Override
                public void onFinish(String filePath) {
                    List<ImageInfo> selectedPhotos = new ArrayList<ImageInfo>();
                    selectedPhotos.add(new ImageInfo(filePath, null, null, 0, 0));
                    if (requestCode == RouterList.FriendCircleBg.REQUEST_FROM_CAMERA_COMMUNITY_BG) {
                        uploadBackgroundImageFile(selectedPhotos);
                    } else {
                        ActivityLauncher.startToPublishActivityWithResult(CommunityActivity.this,
                                RouterList.PublishActivity.MODE_MULTI,
                                selectedPhotos,
                                RouterList.PublishActivity.requestCode);
                    }
                }

                @Override
                public void onError(String msg) {
                    UIHelper.ToastMessage(msg);
                }
            });
        }
    }

    /**
     * @param selectedPhotos
     */
    private void uploadBackgroundImageFile(List<ImageInfo> selectedPhotos) {
        if (selectedPhotos == null) return;
        String[] uploadTaskPaths = new String[selectedPhotos.size()];
        for (int i = 0; i < selectedPhotos.size(); i++) {
            uploadTaskPaths[i] = selectedPhotos.get(i).getImagePath();
        }
        OkHttp3Util.uploadFile(this, OkHttp3Util.uploadHeadImageUrl, uploadTaskPaths, null, null, new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                try {
                    String json = response.body().string();
                    //{"msg":"上传成功","resultCode":0}
                    PublishImageResponse baseResponse = JsonMananger.jsonToBean(json, PublishImageResponse.class);
                    KLog.e("---", "onResponse: " + json);

                    if (baseResponse.getResultCode() == 0) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                request(FRIEND_TRENDS_INFO);
                                ToastUtil.makeToast(getActivity(), "图片上传成功!!");
                            }
                        });
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //request
    //==============================================
    private OnResponseListener.SimpleResponseListener<List<MomentsInfo.DataBean>> momentsRequestCallBack = new OnResponseListener.SimpleResponseListener<List<MomentsInfo.DataBean>>() {
        @Override
        public void onSuccess(List<MomentsInfo.DataBean> response, int requestType) {
            circleRecyclerView.compelete();
            switch (requestType) {
                case REQUEST_REFRESH:
                    if (!ToolUtil.isListEmpty(response)) {
//                        KLog.i("firstMomentid", "第一条动态ID   >>>   " + response.get(0).getMomentid());
                        hostViewHolder.loadHostData();
                        adapter.updateData(response);
                    }
//                    checkRegister();
                    break;
                case REQUEST_LOADMORE:
                    adapter.addMore(response);
                    break;
            }
        }

        @Override
        public void onError(BmobException e, int requestType) {
            super.onError(e, requestType);
            circleRecyclerView.compelete();
        }
    };


    //=============================================================View's method
    @Override
    public void onLikeChange(int itemPos, List<LikesInfo> likeUserList) {
        MomentsInfo.DataBean momentsInfo = adapter.findData(itemPos);
        if (momentsInfo != null) {
            momentsInfo.setLikesList(likeUserList);
            adapter.notifyItemChanged(itemPos);
        }
    }

    @Override
    public void onCommentChange(int itemPos, List<CommentInfo> commentInfoList) {
        MomentsInfo.DataBean momentsInfo = adapter.findData(itemPos);
        if (momentsInfo != null) {
            momentsInfo.setCommentList(commentInfoList);
            adapter.notifyItemChanged(itemPos);
        }
    }

    @Override
    public void showCommentBox(@Nullable View viewHolderRootView, int itemPos, String momentid, CommentWidget commentWidget) {
        if (viewHolderRootView != null) {
            mViewHelper.setCommentAnchorView(viewHolderRootView);
        } else if (commentWidget != null) {
            mViewHelper.setCommentAnchorView(commentWidget);
        }
        mViewHelper.setCommentItemDataPosition(itemPos);
        commentBox.toggleCommentBox(momentid, commentWidget == null ? null : commentWidget.getData(), false);
    }

    @Override
    public void onDeleteMomentsInfo(@NonNull MomentsInfo.DataBean momentsInfo) {
        int pos = adapter.getDatas().indexOf(momentsInfo);
        if (pos < 0) return;
        adapter.deleteData(pos);
    }

    @Override
    public boolean onPreTouch(MotionEvent ev) {
        if (commentBox != null && commentBox.isShowing()) {
            commentBox.dismissCommentBox(false);
            return true;
        }
        return false;
    }

    //=============================================================tool method
//    private void checkRegister() {
//        boolean hasCheckRegister = (boolean) AppSetting.loadBooleanPreferenceByKey(AppSetting.CHECK_REGISTER, false);
//        if (!hasCheckRegister) {
//            RegisterPopup registerPopup = new RegisterPopup(CommunityActivity.this);
//            registerPopup.setOnRegisterSuccess(new RegisterPopup.onRegisterSuccess() {
//                @Override
//                public void onSuccess(UserInfo userInfo) {
//                    hostViewHolder.loadHostData(userInfo);
//                    UpdateInfoManager.INSTANCE.showUpdateInfo();
//                }
//            });
//            registerPopup.showPopupWindow();
//        } else {
//            UpdateInfoManager.INSTANCE.showUpdateInfo();
//        }
//    }

    private long lastClickBackTime;


    //服务器消息检查，非项目所需↓
    private void delayCheckServiceInfo() {
//        Observable.timer(500, TimeUnit.MILLISECONDS)
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Action1<Long>() {
//                    @Override
//                    public void call(Long aLong) {
//                        checkServiceInfo();
//                    }
//                });
    }

    private void checkServiceInfo() {
//        ServiceInfoManager.INSTANCE.check(new ServiceInfoManager.OnCheckServiceInfoListener() {
//            @Override
//            public void onCheckFinish(@Nullable final ServiceInfo serviceInfo) {
//                if (serviceInfo != null) {
//                    mServiceTipsView.setText(serviceInfo.getTips());
//                    mServiceTipsView.setOnClickListener(new SingleClickListener() {
//                        @Override
//                        public void onSingleClick(View v) {
//                            ActivityLauncher.startToServiceInfoActivity(CommunityActivity.this, serviceInfo);
//                            clickServiceCount++;
//                            applyClose();
//                        }
//                    });
//                    mTipsLayout.animate()
//                            .alpha(1)
//                            .translationY(UIHelper.dipToPx(50))
//                            .setDuration(800)
//                            .setInterpolator(new DecelerateInterpolator())
//                            .setListener(new AnimUtils.SimpleAnimatorListener() {
//                                @Override
//                                public void onAnimationStart(Animator animation) {
//                                    mTipsLayout.setVisibility(View.VISIBLE);
//                                }
//
//                                @Override
//                                public void onAnimationEnd(Animator animation) {
//                                    mServiceTipsView.requestFocus();
//                                }
//                            }).start();
//                }
//            }
//        });
    }

    private void applyClose() {
        if (clickServiceCount < 3) return;
        mCloseImageView.setImageResource(R.drawable.ic_close);
        mCloseImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTipsLayout.animate()
                        .alpha(0)
                        .translationY(0)
                        .setDuration(800)
                        .setInterpolator(new DecelerateInterpolator())
                        .setListener(new AnimUtils.SimpleAnimatorListener() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                mTipsLayout.setVisibility(View.GONE);
                            }
                        }).start();
            }
        });
    }
    //服务器消息检查，非项目所需↑

    //=============================================================call back
    private CommentBox.OnCommentSendClickListener onCommentSendClickListener = new CommentBox.OnCommentSendClickListener() {
        @Override
        public void onCommentSendClick(View v, IComment comment, String commentContent) {
            if (TextUtils.isEmpty(commentContent)) {
                commentBox.dismissCommentBox(true);
                return;
            }
            int itemPos = mViewHelper.getCommentItemDataPosition();
            if (itemPos < 0 || itemPos > adapter.getItemCount()) return;
            List<CommentInfo> commentInfos = adapter.findData(itemPos).getCommentList();
            String userid = (comment instanceof CommentInfo) ? ((CommentInfo) comment).getAuthor().getUserid() : null;
            presenter.addComment(CommunityActivity.this, itemPos, commentBox.getMomentid(), userid, commentContent, commentInfos);
            commentBox.clearDraft();
            commentBox.dismissCommentBox(true);
        }
    };


    private class HostViewHolder {
        private View rootView;
        private ImageView friend_wall_pic;
        private ImageView friend_avatar;
        private ImageView message_avatar;
        private TextView message_detail;
        private TextView hostid;

        public HostViewHolder(Context context) {
            this.rootView = LayoutInflater.from(context).inflate(R.layout.circle_host_header, null);
            this.hostid = (TextView) rootView.findViewById(R.id.host_id);
            this.friend_wall_pic = (ImageView) rootView.findViewById(R.id.friend_wall_pic);
            this.friend_avatar = (ImageView) rootView.findViewById(R.id.friend_avatar);
            this.message_avatar = (ImageView) rootView.findViewById(R.id.message_avatar);
            this.message_detail = (TextView) rootView.findViewById(R.id.message_detail);
        }

        public void loadHostData() {
            String userId = sp.getString(SealConst.SEALTALK_LOGIN_ID, "");
            String username = sp.getString(SealConst.SEALTALK_LOGIN_NAME, "");
            String userPortrait = sp.getString(SealConst.SEALTALK_LOGING_PORTRAIT, "");
            if (!TextUtils.isEmpty(userId)) {
                String portraitUri = SealUserInfoManager.getInstance().getPortraitUri
                        (new UserInfo(userId, username, Uri.parse(userPortrait)));
//                ImageLoadMnanger.INSTANCE.loadImage(friend_wall_pic, hostInfo.getCover());
                ImageLoadMnanger.INSTANCE.loadImage(friend_avatar, portraitUri);
                hostid.setText("用户名: " + username);
            }

            /***
             * 朋友圈header图片
             */
            friend_wall_pic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new SelectPhotoMenuPopup(CommunityActivity.this).setOnSelectPhotoMenuClickListener(new SelectPhotoMenuPopup.OnSelectPhotoMenuClickListener() {
                        @Override
                        public void onShootClick() {
                            PhotoHelper.fromCamera(CommunityActivity.this, true, RouterList.FriendCircleBg.REQUEST_FROM_CAMERA_COMMUNITY_BG);
                        }

                        @Override
                        public void onAlbumClick() {
                            ActivityLauncher.startToPhotoSelectActivity(getActivity(), RouterList.FriendCircleBg.requestCode);
                        }
                    }).showPopupWindow();
                }
            });
        }

        public View getView() {
            return rootView;
        }

    }
}
